﻿namespace Lekce03
{
    using System;
    using Microsoft.SPOT.Hardware;
    using SecretLabs.NETMF.Hardware.NetduinoPlus;

    public class Program
    {
        private const int Speed = 100;

        private static readonly Cpu.Pin[] PinList = new Cpu.Pin[]
            {
                Pins.GPIO_PIN_D13,
                Pins.GPIO_PIN_D12,
                Pins.GPIO_PIN_D11,
                Pins.GPIO_PIN_D10,

                Pins.GPIO_PIN_D9,
                Pins.GPIO_PIN_D8,
                Pins.GPIO_PIN_D7,
                Pins.GPIO_PIN_D6
            };

        private static readonly OutputPort[] LedBar = new OutputPort[8];

        private static DateTime nextStep;

        private static int idx = 0;

        private static bool direction = true;

        public static void Main()
        {
            Init();

            while (true)
            {
                WormMove();
                // KnightRider();
            }
        }

        private static void Init()
        {
            for (int n = 0; n < LedBar.Length; n++)
            {
                LedBar[n] = new OutputPort(PinList[n], false);
            }
            nextStep = DateTime.Now;
        }

        private static void KnightRider()
        {
            if (nextStep < DateTime.Now)
            {
                if (direction)
                {
                    LedBar[idx].Write(false);
                    idx++;
                    LedBar[idx].Write(true);
                }
                else
                {
                    LedBar[idx].Write(false);
                    idx--;
                    LedBar[idx].Write(true);
                }

                idx = idx % LedBar.Length;
                if (idx == 0 || idx == LedBar.Length - 1)
                {
                    direction = !direction;
                }

                nextStep = DateTime.Now.AddMilliseconds(Speed);
            }
        }

        private static void WormMove()
        {
            if (nextStep < DateTime.Now)
            {
                LedBar[idx].Write(false);
                idx++;
                idx = idx % LedBar.Length;
                LedBar[idx].Write(true);
                nextStep = DateTime.Now.AddMilliseconds(Speed);
            }
        }
    }
}
